package cn.mifengkong.appcommon.webview.jshandler;

import android.content.Context;
import android.util.Log;

import com.mifengkong.frtools.jsbridge.CallBackFunction;
import com.mifengkong.frtools.jsbridge.JsHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.mifengkong.appcommon.webview.BitmapDownloadIntentService;

/**
 * Created on 2018/3/6
 *
 * @author jiang
 */

public class ImageDownLoadHandler implements JsHandler {

    private final Context context;
    private String[] imageUrlStrs;

    public ImageDownLoadHandler(Context context) {
        this.context = context;
    }

    @Override
    public void OnHandler(String handlerName, String responseData, CallBackFunction function) {
        if (parseResponseData(responseData) && context != null) {
            BitmapDownloadIntentService.startForSaveBasicInfo(context, imageUrlStrs);
        }
    }

    /**
     * 是否需要跳转支付页面
     */
    private boolean parseResponseData(String responseData) {
        try {
            JSONObject responseDataJO = new JSONObject(responseData);
            JSONArray imageUrls = responseDataJO.getJSONArray("image_url_array");
            if (imageUrls == null) {
                return false;
            }
            imageUrlStrs = new String[imageUrls.length()];
            for (int i = 0; i < imageUrls.length(); i++) {
                imageUrlStrs[i] = String.valueOf(imageUrls.get(i));
                Log.e("jiang", "parseResponseData:" + imageUrls.get(i));
            }
            return imageUrlStrs.length > 0;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }
}
